package com.hxs.learn.action.core;

import java.awt.image.BufferedImage;

import java.io.IOException;

import javax.imageio.ImageIO;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

import com.hxs.learn.common.result.Result;
import com.hxs.learn.common.web.LoginInfo;
import com.hxs.learn.common.web.annotation.Login;
import com.hxs.learn.common.web.utils.WebUtil;
import com.hxs.learn.service.core.SysMenuService;

import io.swagger.annotations.ApiOperation;

/**
 * @author HuXinsheng
 */
@RestController
public class IndexAction {
    private static final Logger  log = LoggerFactory.getLogger(IndexAction.class);
    private final Producer       producer;
    private final SysMenuService sysMenuService;

    @Autowired
    public IndexAction(Producer producer, SysMenuService sysMenuService) {
        this.producer       = producer;
        this.sysMenuService = sysMenuService;
    }

    @ApiOperation(
        value = "获取图形验证码",
        notes = "用户登录时要使用的图形验证码"
    )
    @GetMapping(value = "captcha")
    public void captcha(HttpServletResponse response) {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        // 生成文字验证码
        String text = producer.createText();

        // 生成图片验证码
        BufferedImage image = producer.createImage(text);

        // 保存到shiro session
        WebUtil.getShiroSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, text);

        try {
            ServletOutputStream out = response.getOutputStream();

            ImageIO.write(image, "jpg", out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(
        value = "获取用户菜单",
        notes = "登录成功后获取当前用户菜单信息"
    )
    @GetMapping("getMenus")
    public Result getMenus(@Login LoginInfo userInfo) {
        String userId = userInfo.getUserId();
        return Result.ok(sysMenuService.findByUserId(userId));
    }
}


//~ Formatted by Jindent --- http://www.jindent.com
